<template>
	<div class="m-l-50 m-t-30 w-500">
		<el-form ref="form" :model="form" :rules="rules" label-width="130px">
			<el-form-item label="用户名" prop="username">
				<el-input v-model.trim="form.username" class="h-40 w-200" :maxlength=12 :disabled="this.$route.params.id"></el-input>
			</el-form-item>
      <el-form-item label="密码" prop="password" >
        <el-input v-model.trim="form.password" class="h-40 w-200" placeholder="不填则保持原密码"></el-input>
      </el-form-item>
			<el-form-item label="真实姓名" prop="realname">
				<el-input v-model.trim="form.realname" class="h-40 w-200"></el-input>
			</el-form-item>
			<el-form-item label="部门" prop="structure_id">
				<el-select v-model="form.structure_id" placeholder="部门" v-on:change="selectStructure()" class="w-200">
					<el-option v-for="item in structureOptions" :label="item.name" :value="item.id" :key="item.post_id"></el-option>
				</el-select>
			</el-form-item>
      <el-form-item label="岗位" prop="post_id">
        <el-select v-model="form.post_id" placeholder="岗位" class="w-200">
          <el-option v-for="item in postOptions" :label="item.name" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
			<el-form-item label="备注">
				<el-input v-model.trim="form.remark" class="h-40 w-200"></el-input>
			</el-form-item>
			<el-form-item label="角色">
				<el-checkbox-group v-model="selectedGroup">
					<el-checkbox v-for="item in groupOptions" :label="item.title" class="form-checkbox" :key="item.id"></el-checkbox>
				</el-checkbox-group>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="save()" :loading="isLoading">提交</el-button>
				<el-button @click="goback()">返回</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>
<style>
	.form-checkbox:first-child{
		margin-left: 15px;
	}
</style>
<script>
  import http from '../../../../assets/js/http'
  import fomrMixin from '../../../../assets/js/form_com'
  import _ from 'lodash'
  import _g from '@/assets/js/global'
  import { Button, Dialog, Form, FormItem, Input, Select, Option, CheckboxGroup, Checkbox } from 'element-ui'
  Vue.use(Button)
  Vue.use(Form)
  Vue.use(FormItem)
  Vue.use(Input)
  Vue.use(Select)
  Vue.use(Option)
  Vue.use(CheckboxGroup)
  Vue.use(Checkbox)

  export default {
    data() {
      return {
        isLoading: false,
        id: null,
        form: {
          username: '',
          realname: '',
          password: '',
          structure_id: null,
          post_id: null,
          remark: '',
          groups: []
        },
        password: '',
        structureOptions: [],
        postOptions: [],
        groupOptions: [],
        selectedGroup: [],
        selectedIds: [],
        rules: {
          username: [
            { required: true, message: '请输入用户名' }
          ],
          realname: [
            { required: true, message: '请输入真实姓名' }
          ],
          structure_id: [
            { required: true, message: '请选择用户部门' }
          ],
          post_id: [
            { required: true, message: '请选择岗位' }
          ]
        }
      }
    },
    methods: {
      save(form) {
        if (this.$route.params.id) {
          this.edit(form)
        } else {
          this.add(form)
        }
      },
      add(form) {
        if (!this.selectCheckbox()) {
          _g.toastMsg('warning', '请选择角色')
          return
        }
        this.$refs.form.validate((pass) => {
          if (pass) {
            this.isLoading = true
            this.apiPost('admin/admin', this.form).then((res) => {
              this.handelResponse(res, (data) => {
                this.isLoading = false
                _g.toastMsg('success', '添加成功')
                _g.clearVuex('setUser')
                setTimeout(() => {
                  this.goback()
                }, 1500)
              }, () => {
                this.isLoading = false
              })
            })
          }
        })
      },
      selectStructure() {
        let i = 0
        let post_id = null
        for (i = 0; i < this.structureOptions.length; i++) {
          if (this.structureOptions[i].structure_id == this.form.structure_id) {
            this.postOptions = this.structureOptions[i].posts
            break
          }
        }
        for (i = 0; i < this.postOptions.length; i++) {
          if (this.postOptions[i].post_id == this.form.post_id) {
            post_id = this.form.post_id
            break
          }
        }
        this.form.post_id = post_id
      },
      selectCheckbox() {
        let temp = false
        _(this.groupOptions).forEach((res) => {
          if (this.selectedGroup.toString().indexOf(res.title) > -1) {
            this.selectedIds.push(res.id)
          }
        })
        if (this.selectedIds.length) {
          this.form.groups = _.cloneDeep(this.selectedIds)
          temp = true
        }
        this.selectedIds = []
        return temp
      },
      edit() {
        if (!this.selectCheckbox()) {
          _g.toastMsg('warning', '请选择角色')
          return
        }
        this.$refs.form.validate((pass) => {
          if (pass) {
            this.isLoading = true
            if (this.password) {
              this.form.password = this.password
            }
            this.apiPut('admin/admin/', this.id, this.form).then((res) => {
              this.handelResponse(res, (data) => {
                this.isLoading = false
                _g.toastMsg('success', '编辑成功')
                _g.clearVuex('setUser')
                setTimeout(() => {
                  this.goback()
                }, 1500)
              }, () => {
                this.isLoading = false
              })
            })
          }
        })
      },
      getAllGroup() {
        this.apiGet('admin/group', { 'limit': 500 }).then((res) => {
          this.handelResponse(res, (data) => {
            this.groupOptions = data.list
          })
        })
      },
      getAllStructure() {
        this.apiGet('admin/structure', { 'limit': 500 }).then((res) => {
          this.handelResponse(res, (data) => {
            this.structureOptions = []
            _(data.list).forEach((ret) => {
              if (ret.posts.length > 0) {
                // 过滤掉没有岗位的
                this.structureOptions.push(ret)
              }
            })
            this.selectStructure()
          })
        })
      },
      async getCompleteData() {
        await this.getAllStructure()
        await this.getAllGroup()
        this.apiGet('admin/admin/' + this.id).then((res) => {
          this.handelResponse(res, (data) => {
            this.form.username = data.info.username
            this.form.realname = data.info.realname
            this.form.structure_id = data.info.structure_id
            this.form.remark = data.info.remark
            this.form.post_id = data.info.post_id
            _(data.info.groups).forEach((res1) => {
              _(this.groupOptions).forEach((res2) => {
                if (res1.group_id == res2.group_id) {
                  this.selectedGroup.push(res1.title)
                }
              })
            })
          })
        })
      }
    },
    created() {
      if (this.$route.params.id) {
        this.id = this.$route.params.id
        this.getCompleteData()
      } else {
        this.getAllStructure()
        this.getAllGroup()
      }
    },
    mixins: [http, fomrMixin]
  }
</script>
